var defaultStageName = "某一阶段打分";
$(function () {
    /**
     * 电子钟表
     */
    var clock = document.querySelector('.clock > span');
    (function setClock() {
        var now = new Date();
        clock.innerHTML = now.getFullYear() + '年' + (parseInt(now.getMonth()) + 1) + "月" + now.getDate() + "日 "
            + now.toTimeString().split(' ')[0];
        window.setTimeout(setClock, 1000);
    })();

    /**
     * 开关监听
     */
    switchEvent("#mark_kg", function() {
        // 开启打分
        show_();
    }, function() {
        // 关闭打分，同时会进行阶段打分的统计
        var c = confirm("确定关闭该阶段打分吗？");
        if (c) {
            var $ms     = $('#mark_kg');
            var stageId = $ms.data('stage');
            $("#no_has").removeClass("hidden");
            $("#has").addClass("hidden");
            $.post("/mark/switch/0", {id: stageId});
        } else {
            honeySwitch.showOn("#mark_kg");
        }
    });

    /*
    开启二维码打分，添加新的打分阶段
     */
    $('form').submit(function (e) {
        e.preventDefault();
        $('#loading').removeClass('hidden');
        var name = $('form input[name=name]').val() || defaultStageName;
        var ids = [];
        $.each($('input[type="checkbox"]:checked'), function (k, v) {
            ids.push(v.value);
        });

        $.post("/stage/add", {name: name, shopIds: ids.join("|")}, function (data) {
            if (data.success) {
                var stage = data.data;
                $.post("/mark/switch/1", {id: stage['id'], name: stage['name']}, function (data) {
                    var has = $("#has");
                    var no_has = $("#no_has");
                    if (data.success) {
                        var img = has.removeClass("hidden").find("img");
                        img.attr("data-url", data.data.code).attr("src", data.data.url);

                        $("a#download").attr('href', data.data.download);
                        $('#has .label-info').html("参与人数：" + stage['userSum']);
                        $('#has .label-success').html("打分阶段：" + stage['name']);
                        $('#has .can-off').attr('class', 'can-on');
                        $('#mark_kg').data('stage', stage["id"]).data('name', stage["name"]).data('ids', stage["shopIds"]);
                        no_has.addClass("hidden");
                        close_(false);
                    } else {
                        no_has.removeClass("hidden");
                        has.addClass("hidden")
                    }
                });
            }
        });
    });

    // 打开修改阶段信息选择框
    $('#change_box').click(function (e) {
        var $kg = $('#mark_kg');
        var stageId = $kg.data('stage');
        var stageName = $kg.data('name');
        var shopIds = $kg.data('ids') + '';
        var $model = $('.stage_add');

        $model.find('input[name=id]').val(stageId);
        $model.find('input[name=name]').val(stageName);
        $model.find('a').attr('onclick', 'close_(false);'); // 控制关闭是否同时关上开关
        $model.find('button.btn-danger').attr('onclick', 'close_(false);');

        var strs = shopIds.indexOf('|') > 0 ? shopIds.split('|') : [shopIds, '-1'];
        $.each($model.find('input[type=checkbox]'), function (k, v) {
            var id = v.value;
            if (strs.indexOf(id) >= 0) {
                $(v).attr('checked', 'checked');
            }
        });

        $model.removeClass('hidden'); // 显示打分启动选择框
        $model.find('button[type=submit]').addClass('hidden'); // 控制修改显隐
        $model.find('#change_stage').removeClass('hidden');
    });

    // 完成阶段信息修改
    $('#change_stage').click(function (e) {
        e.preventDefault();
        var id = $('form input[name=id]').val();
        var name = $('form input[name=name]').val() || defaultStageName;
        var ids = [];
        $.each($('.stage_add input[type="checkbox"]:checked'), function (k, v) {
            ids.push(v.value);
        });

        $.post('/stage/change', {
            id: id,
            name: name,
            shopIds: ids.join('|')
        }, function (data) {
            if (data.success) {
                alert("" + data.msg);
                location.reload();
            }
            close_(false);
        })
    });
});

/**
 * 关闭添加打分阶段的弹出框
 * @param no 不存在则同时关闭打分开关，不触发开关的close监听
 */
function close_(no) {
    $('.stage_add').addClass('hidden');
    $('#loading').addClass('hidden');
    if (no === undefined) {
        honeySwitch.showOff("#mark_kg");
    }
}

/**
 * 打开添加打分阶段弹出框，同时设置默认打分阶段为按月的旬
 */
function show_() {
    var $model = $('.stage_add');
    $model.removeClass('hidden'); // 显示打分启动选择框
    $model.find('button[type=submit]').removeClass('hidden'); // 控制修改显隐
    $model.find('#change_stage').addClass('hidden');

    $model.find('a').attr('onclick', 'close_();'); // 控制关闭是否同时关上开关
    $model.find('button.btn-danger').attr('onclick', 'close_();');

    var date  = new Date();
    var year  = date.getFullYear();
    var month = date.getMonth() + 1;
    var day   = date.getDate();
    var name = "2018年5月上旬";
    switch (true) {
        case day <= 10:
            name = year + "年" + month + "月上旬";
            break;
        case day > 20:
            name = year + "年" + month + "月下旬";
            break;
        default:
            name = year + "年" + month + "月中旬";
            break;
    }
    defaultStageName = name;
    $("#stage > input").val(defaultStageName + "-打分");
}

/**
 *  打分控制暂停和重新开始
 * @param self
 */
/*function can_switch(self) {
    var span = $(self).find('span');
    var stageId = $('#mark_kg').data('stage');
    if (span.attr('class') === 'can-on') {
        $.post('/mark/pause', function (data) {
            if (data.success) {
                $("a#download").attr('href', '');
                $(self).removeClass('btn-warning').addClass('btn-success');
                $('#has img').attr("src", '/static/images/admin/pause.png');
                span.attr('class', 'can-off');
            }
        });
    } else {
        $.post('/mark/restart', {stageId: stageId}, function (data) {
            if (data.success) {
                $("a#download").attr('href', data.data.download);
                $(self).removeClass('btn-success').addClass('btn-warning');
                $('#has img').attr("data-url", data.data.code).attr("src", data.data.url);
                span.attr('class', 'can-on');
            }
        });
    }
}*/

/*
function fillStage() {

}

function fillImg() {

}
*/